# -*- coding: UTF-8 -*-
import random
"""
    感知机过程演示
"""


class Perceptron_demo:
    def __init__(self):
        self._w_ = [[0, 0]]
        self.j = 0
        self._b_ = [0]
        self.X = [[4, 3], [3, 3], [1, 1]]
        self.Y = [1, 1, -1]

    # 判断是否为错误分类
    def wrong_class(self, i):
        sign_val = self._w_[self.j][0] * self.X[i][0] + self._w_[self.j][1] * self.X[i][1] + self._b_[self.j]
        print("signVal=" + str(sign_val) + " ,y=" + str(self.Y[i]))
        return self.Y[i] * sign_val <= 0

    def find_wrong_class(self):
        print("第" + str(self.j) + "次")
        i_box = []
        while(len(i_box) < len(self.X)):
            i = random.randint(0, len(self.X) - 1)
            old_box_len = len(i_box)
            i_box.append(i)
            if(old_box_len == len(set(i_box))):
                continue
            X_str = "[" + ",".join('%s' % id for id in self.X[i]) + "]"
            print("验证 X[" + str(i) + "]：" + X_str + " , w=" + str(self._w_[self.j]) + " ,b=" + str(self._b_[self.j]))
        # for i in range(len(self.X)):
        #     X_str = "[" + ",".join('%s' %id for id in self.X[i]) + "]"
        #     print("验证 X[" + str(i) + "]：" + X_str + " , w=" + str(self._w_[self.j]) + " ,b=" + str(self._b_[self.j]))
            if (self.wrong_class(i)):
                return i
        return -1

    def update(self, i):
        j_tmp = self.j
        self.j += 1
        w = [self._w_[j_tmp][0] + self.X[i][0] * self.Y[i],
             self._w_[j_tmp][1] + self.X[i][1] * self.Y[i]]
        self._w_.append(w)
        self._b_.append(self._b_[j_tmp] + self.Y[i])

    def test(self):
        re = 0
        while (re != -1):
            re = self.find_wrong_class()
            self.update(re)
        print(self._w_)
        print(self._b_)


if __name__ == '__main__':
    perceptron_demo = Perceptron_demo()
    perceptron_demo.test()
